/**
 * 2009-10-25 下午01:11:26 
 * esignature
 * com.smc.security.util
 * CoderUtil
 */
package com.smc.security.util;

import java.security.MessageDigest;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author chenheng
 * @version 0.0.1
 * 编码加密工具
 */
public abstract class CoderUtil {
	public static final String KEY_SHA = "SHA-1";       
    public static final String KEY_MD5 = "MD5";   
    /**
     * BASE64解码
     * @param key	要解码的字符串
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {       
        return (new BASE64Decoder()).decodeBuffer(key);       
    }       
    /**
     * BASE64编码
     * @param key	要编码的二进制串
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {       
        return (new BASE64Encoder()).encodeBuffer(key);       
    }  
    /**
     * MD5编码
     * @param data	要编码的MD5二进制串
     * @return
     * @throws Exception
     */
    public static byte[] encryptMD5(byte[] data) throws Exception {       
        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);       
        md5.update(data);             
        return md5.digest();       
    }       
    /**
     * SHA-1编码
     * @param data	要编码的SHA-1二进制串
     * @return
     * @throws Exception
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {       
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);       
        sha.update(data);       
        return sha.digest();       
    }
    /**
     * 二进制流转字符串
     * @param code	要转字符串的二进制流
     * @return
     */
    public static String byte2hex(byte[] code) {
    	String hex="";
    	String temp = "";
    	for ( int i=0;i<code.length;i++) {
    		temp = Integer.toHexString(code[i] & 0xFF);
    		if ( temp.length() == 1) {
    			hex = hex + "0" + temp ; 
    		} else {
    			hex = hex + temp ;
    		}
    	}
    	return hex.toUpperCase();
    }
}
